﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;

namespace PRI_SliverlightSS
{
    public class PRI_PicasaFeedReader : PRI_Albums
    {
        //http://picasaweb.google.com/data/feed/api/user/clickalbum?kind=album
        const string PICASA_ALBUMS_FEED = "http://picasaweb.google.com/data/feed/api/user/{0}?kind=album";
        const string PICASA_ALBUM_PHOTO_FEED = "http://picasaweb.google.com/data/feed/api/user/{0}/albumid/{1}?kind=photo";
        string m_PicasaUsername = string.Empty;

        public string PicasaUsername
        {
            get
            {
                return m_PicasaUsername;
            }
        }

        public void GetAlbums(string _picasa_username)
        {
            base.m_AlbumType = AlbumType.AT_Picasa;
            m_PicasaUsername = _picasa_username;

            string strAlbumsURL = string.Format(PICASA_ALBUMS_FEED, _picasa_username);
            GetAlbumsFromURL(strAlbumsURL);
        }

        public void GetAlbumsFromURL(string _url)
        {
            WebClient oWebClient_GetAlbums = new WebClient();
            oWebClient_GetAlbums.OpenReadCompleted += new OpenReadCompletedEventHandler(this.oWebClient_GetAlbums_OpenReadCompleted);
            oWebClient_GetAlbums.OpenReadAsync(new Uri(string.Format(this.ProxyURL, _url)));   //(new Uri(_url));
        }

        void oWebClient_GetAlbums_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (null == e.Result)
            {
                this._LastError.ErrorCode = SSError.eErrorCodes.SomeError;
                this._LastError.Message = "Result is Empty";
            }
            else if (e.Cancelled)
            {
                this._LastError.ErrorCode = SSError.eErrorCodes.SomeError;
                this._LastError.Message = "Operation cancelled";
            }
            else
            {
                GetAlbumsFromURL_OpenStreamCompleted(e.Result);
            }

            try
            {
                this.FireEvent_AlbumsReady();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        void GetAlbumsFromURL_OpenStreamCompleted(Stream _stream)
        {
            try
            {
                this._LastError.Clear();

                string strTemp = "";
                // Create a new StreamReader instance using the specified Stream object.
                //string nsXMLNS = "http://www.w3.org/2005/Atom";
                //string nsMEDIA = "http://search.yahoo.com/mrss/";
                //string nsGPHOTO = "http://schemas.google.com/photos/2007";

                /*
                XNamespace.Xmlns.NamespaceName
                ((XElement)document.Document.FirstNode).Attribute("{" + XNamespace.Xmlns.NamespaceName + "}gphoto").Value
                "http://schemas.google.com/photos/2007"
                ((XElement)document.Document.FirstNode).Element("{http://www.w3.org/2005/Atom}id").Value
                "http://picasaweb.google.com/data/feed/api/user/clickalbum"
                ((XElement)document.Document.FirstNode).Element("{http://www.w3.org/2005/Atom}updated").Value
                "2008-09-03T19:24:29.577Z"
                */

                using (StreamReader streamreader = new StreamReader(_stream))
                {
                    XDocument document = XDocument.Load(streamreader);

                    XNamespace nsDefault = ((XElement)document.Document.FirstNode).Attribute("xmlns").Value;
                    XNamespace nsMedia = ((XElement)document.Document.FirstNode).Attribute("{" + XNamespace.Xmlns.NamespaceName + "}media").Value;
                    XNamespace nsGPhoto = ((XElement)document.Document.FirstNode).Attribute("{" + XNamespace.Xmlns.NamespaceName + "}gphoto").Value;
                    try
                    {
                        string strLastUpdated = ((XElement)document.Document.FirstNode).Element(nsDefault + "updated").Value;
                        string strAuthor_name = ((XElement)document.Document.FirstNode).Element(nsDefault + "author").Element(nsDefault + "name").Value;
                        string strAuthorURL = ((XElement)document.Document.FirstNode).Element(nsDefault + "author").Element(nsDefault + "uri").Value;
                        this.SetAuthorInfo(strAuthor_name, strAuthorURL, strLastUpdated);
                    }
                    catch (Exception)
                    {
                        //No big deal
                    }

                    XElement oxeFN = (XElement)document.Document.FirstNode;

                    var qryAlbums_Info = from tblEntry in oxeFN.Elements(nsDefault + "entry")
                            //orderby oxeFN.Element(nsDefault + "entry").Element(nsDefault + "published").Value ascending
                            select new PRI_Album_Info
                            {
                                _id = tblEntry.Element(nsGPhoto + "id").Value,
                                _title = tblEntry.Element(nsMedia + "group").Element(nsMedia + "title").Value,
                                _content_url = tblEntry.Element(nsMedia + "group").Element(nsMedia + "content").Attribute("url").Value,
                                _thumbnail_url = tblEntry.Element(nsMedia + "group").Element(nsMedia + "thumbnail").Attribute("url").Value,
                                _published_datetime = tblEntry.Element(nsDefault + "published").Value
                            };

                    foreach (PRI_Album_Info _pri_album_info in qryAlbums_Info)
                    {
                        this.AddAlbum(_pri_album_info._id, _pri_album_info._title, _pri_album_info._content_url, _pri_album_info._thumbnail_url, _pri_album_info._published_datetime);
                    }

/*                    
                    XElement oxeFN = (XElement)document.Document.FirstNode;
                    var vEntry = oxeFN.Elements(nsDefault + "entry");

                    string strID = "";
                    string strTitle = "";
                    string strContentURL = "";
                    string strThumbnailURL = "";

                    foreach (XElement _entry in vEntry)
                    {
                        strID = ((XElement)_entry.Element(nsGPhoto + "id")).Value;
                        strTitle = _entry.Element(nsMedia + "group").Element(nsMedia + "title").Value;
                        strContentURL = _entry.Element(nsMedia + "group").Element(nsMedia + "content").Attribute("url").Value;
                        strThumbnailURL = _entry.Element(nsMedia + "group").Element(nsMedia + "thumbnail").Attribute("url").Value;

                        this.AddAlbum(strID, strTitle, strContentURL, strThumbnailURL);
                    }*/

                    var feeds = ((XElement)document.Document.FirstNode).Attributes();
                    foreach (XAttribute _att in feeds)
                    {
                        strTemp = _att.Name.LocalName;
                        strTemp = _att.Name.Namespace.NamespaceName;
                        strTemp = _att.Name.NamespaceName;
                        strTemp = _att.Value;
                    }
                }
            }
            catch (Exception ex)
            {
                this._LastError.ErrorCode = SSError.eErrorCodes.SomeError;
                this._LastError.Message = ex.ToString();
            }
        }

        public void GetAlbumSlides(string _picasa_username, string _album_id)
        {
            try
            {
                this._CurrentSlides.Clear();

                string strAlbumsURL = string.Format(PICASA_ALBUM_PHOTO_FEED, _picasa_username, _album_id);

                WebClient oWebClient_GetAlbumSlides = new WebClient();
                oWebClient_GetAlbumSlides.OpenReadCompleted += new OpenReadCompletedEventHandler(this.oWebClient_GetAlbumSlides_OpenReadCompleted);
                oWebClient_GetAlbumSlides.OpenReadAsync(new Uri(string.Format(this.ProxyURL, strAlbumsURL)));   //(new Uri(_url));

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        void oWebClient_GetAlbumSlides_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (null == e.Result)
            {
                throw new Exception("Result is Empty");
            }
            else if (e.Cancelled)
            {
                throw new Exception("Operation cancelled");
            }
            else
            {
                GetAlbumSlides_OpenStreamCompleted(e.Result);
            }

            try
            {
                this.FireEvent_SlidesReady(); //FireEvent
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        void GetAlbumSlides_OpenStreamCompleted(Stream _stream)
        {
            try
            {
                string strTemp = "";

                /*
                XNamespace.Xmlns.NamespaceName
                ((XElement)document.Document.FirstNode).Attribute("{" + XNamespace.Xmlns.NamespaceName + "}gphoto").Value
                "http://schemas.google.com/photos/2007"
                ((XElement)document.Document.FirstNode).Element("{http://www.w3.org/2005/Atom}id").Value
                "http://picasaweb.google.com/data/feed/api/user/clickalbum"
                ((XElement)document.Document.FirstNode).Element("{http://www.w3.org/2005/Atom}updated").Value
                "2008-09-03T19:24:29.577Z"
                */

                using (StreamReader streamreader = new StreamReader(_stream))
                {
                    XDocument document = XDocument.Load(streamreader);

                    XNamespace nsDefault = ((XElement)document.Document.FirstNode).Attribute("xmlns").Value;
                    XNamespace nsMedia = ((XElement)document.Document.FirstNode).Attribute("{" + XNamespace.Xmlns.NamespaceName + "}media").Value;
                    XNamespace nsGPhoto = ((XElement)document.Document.FirstNode).Attribute("{" + XNamespace.Xmlns.NamespaceName + "}gphoto").Value;

                    strTemp = ((XElement)document.Document.FirstNode).Element(nsDefault + "updated").Value;

                    var vEntry = ((XElement)document.Document.FirstNode).Elements(nsDefault + "entry");

                    foreach (XElement _entry in vEntry)
                    {
                        PRI_Slide oPRI_Album_Photo = new PRI_Slide();

                        oPRI_Album_Photo._id = ((XElement)_entry.Element(nsGPhoto + "id")).Value;
                        oPRI_Album_Photo._title = _entry.Element(nsMedia + "group").Element(nsMedia + "title").Value;
                        oPRI_Album_Photo._content_url = _entry.Element(nsMedia + "group").Element(nsMedia + "content").Attribute("url").Value;
                        oPRI_Album_Photo._description = _entry.Element(nsMedia + "group").Element(nsMedia + "description").Value;

                        var qryThumbs = from tableThumbs in _entry.Element(nsMedia + "group").Elements(nsMedia + "thumbnail")
                                orderby double.Parse(tableThumbs.Attribute("width").Value) ascending
                                select new PRI_Slide_Thumb
                                {
                                    _url = tableThumbs.Attribute("url").Value,
                                    _height = double.Parse(tableThumbs.Attribute("height").Value),
                                    _width = double.Parse(tableThumbs.Attribute("width").Value)
                                };

                        foreach (PRI_Slide_Thumb _t in qryThumbs)
                        {
                            oPRI_Album_Photo.SetThumb(_t);
                        }

                        this._CurrentSlides.AddPhoto(oPRI_Album_Photo);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
